#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "typedef.h"
#include "common.h"
#include "package.h"

static void create_package(PPACKAGE buffer, unsigned char* data, int size)
{
	buffer->header = 0x00;
	memcpy(buffer->data, data, size);
	buffer->tail   = 0xFF;
}

int pkg_get(PDATA_PACKAGE package, unsigned char* buffer, int size)
{
	if ( size != sizeof( PACKAGE ) ){
		return ERROR;
	}

	PPACKAGE p = (PPACKAGE)buffer;
	if ( p->header != 0x00
			|| p->tail != 0xFF ){
		return ERROR;
	}

	PDATA_PACKAGE data = (PDATA_PACKAGE)p->data;
	package->type = ntohl ( data->type );
	package->length = ntohl ( data->length );
	if ( package->length > 0 ){
		memcpy(package->command,
				data->command,
				package->length
				);
	}

	return SUCCESS;
}

void pkg_create_handshakeack_package(PPACKAGE buffer, int cpus, int serverid)
{
	HANDSHAKE_ACK_PACKAGE handshake;
	handshake.type = PT_HANDSHAKE_ACK;
	handshake.length = 2 * sizeof ( unsigned int );
	handshake.serverid = serverid;
	handshake.cpus = cpus;

	create_package(buffer,
			(unsigned char*)&handshake,
			sizeof(HANDSHAKE_ACK_PACKAGE)
			);
}

void pkg_create_finish_package(PPACKAGE buffer, int id)
{
	FINISH_PACKAGE finish;
	finish.type = PT_FINISH;
	finish.length = sizeof (int);
	finish.id = id;

	create_package(buffer,
			(unsigned char*)&finish,
			sizeof(FINISH_PACKAGE)
			);
}

void pkg_create_runack_package(PPACKAGE buffer, int id)
{
	RUN_ACK_PACKAGE run;
	run.type = PT_RUN_ACK;
	run.length = sizeof (int);
	run.id = id;

	create_package(buffer,
			(unsigned char*)&run,
			sizeof(RUN_ACK_PACKAGE)
			);
}

